package lookie.swing.tree.model.util;

import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeModel;

import lookie.swing.tree.model.DeferredTreeNode;
import lookie.swing.tree.model.TreeNodeProvider;

public class DeferredTreeNodeWillExpandListener extends
		LazyTreeNodeWillExpandListener {

	public DeferredTreeNodeWillExpandListener(TreeNodeProvider provider) {
		super(provider);
	}

	public void treeWillExpand(final TreeExpansionEvent event)
			throws ExpandVetoException {
		Object lastComponent = event.getPath().getLastPathComponent();
		if (lastComponent instanceof DeferredTreeNode) {
			final DeferredTreeNode node = (DeferredTreeNode) lastComponent;
			if (node.isDeferred()) {
				final JTree tree = (JTree) event.getSource();
				DeferredTreeNodeLoader loader = new DeferredTreeNodeLoader(getProvider()) {

					@Override
					public void postDeferred(DeferredTreeNode parent) {
						notifyTree(tree, node);
					}
					
				};
				loader.load(node);
				notifyTree(tree, node);
			} else {
				super.treeWillCollapse(event);
			}
		} else {
			super.treeWillCollapse(event);
		}

	}
	
	private void notifyTree(JTree tree, DeferredTreeNode node) {
		TreeModel model = tree.getModel();
		if (model instanceof DefaultTreeModel) {
			((DefaultTreeModel) model)
					.nodeStructureChanged(node);
		}
	}
	
}
